//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { observer } from 'mobx-react';
import { useStores } from "@/hooks";
import { Form, Input, message, Modal, Select, Space } from "antd";
import type { EvaluateTargetInfo, EvaluateInfo } from "@/api/org_evaluate";
import { list_target, create_evaluate, update_base_for_evaluate } from "@/api/org_evaluate";
import { request } from "@/utils/request";
import UserPhoto from "@/components/Portrait/UserPhoto";

export interface EditEvalModalProps {
    departMentId: string;
    evalInfo?: EvaluateInfo;
    onCancel: () => void;
    onOk: () => void;
}

const EditEvalModal = (props: EditEvalModalProps) => {
    const userStore = useStores("userStore");
    const orgStore = useStores("orgStore");

    const genTargetIdList = () => {
        if (props.evalInfo == undefined) {
            return [];
        }
        if (props.evalInfo.member_list.length == 0) {
            return [];
        }
        return props.evalInfo.member_list[0].score_list.map(item => item.target_id);
    };

    const [targetInfoList, setTargetInfoList] = useState<EvaluateTargetInfo[]>([]);
    const [title, setTitle] = useState(props.evalInfo?.evaluate_title ?? "");
    const [desc, setDesc] = useState(props.evalInfo?.evaluate_desc ?? "");
    const [memberUserIdList, setMemberUserIdList] = useState<string[]>((props.evalInfo?.member_list ?? []).map(item => item.member_user_id));
    const [targetIdList, setTargetIdList] = useState<string[]>(genTargetIdList());

    const loadTargetInfoList = async () => {
        const res = await request(list_target({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
        }));
        setTargetInfoList(res.target_list);
    };

    const createEval = async () => {
        await request(create_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            depart_ment_id: props.departMentId,
            evaluate_title: title,
            evaluate_desc: desc,
            member_user_id_list: memberUserIdList,
            target_id_list: targetIdList,
        }));
        message.info("增加成功");
        props.onOk();
    };

    const updateEval = async () => {
        if (props.evalInfo == undefined) {
            return;
        }
        await request(update_base_for_evaluate({
            session_id: userStore.sessionId,
            org_id: orgStore.curOrgId,
            evaluate_id: props.evalInfo.evaluate_id,
            evaluate_title: title,
            evaluate_desc: desc,
            member_user_id_list: memberUserIdList,
            target_id_list: targetIdList,
        }));
        message.info("更新成功");
        props.onOk();
    };

    useEffect(() => {
        loadTargetInfoList();
    }, []);

    return (
        <Modal open title={`${props.evalInfo == undefined ? "增加" : "更新"}评估`} mask={false}
            okText={props.evalInfo == undefined ? "增加" : "更新"} okButtonProps={{ disabled: !(title != "" && targetIdList.length != 0 && memberUserIdList.length >= 3) }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onCancel();
            }}
            onOk={e => {
                e.stopPropagation();
                e.preventDefault();
                if (props.evalInfo == undefined) {
                    createEval();
                } else {
                    updateEval();
                }
            }}>
            <Form labelCol={{ span: 3 }}>
                <Form.Item label="名称">
                    <Input value={title} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setTitle(e.target.value.trim());
                    }} status={title == "" ? "error" : undefined} />
                </Form.Item>
                <Form.Item label="评估要求">
                    <Input.TextArea autoSize={{ minRows: 3, maxRows: 3 }} value={desc} onChange={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setDesc(e.target.value);
                    }} placeholder="可选" />
                </Form.Item>
                <Form.Item label="参加成员" help={
                    <>
                        {memberUserIdList.length < 3 && <span style={{ color: "red" }}>必须3人以上</span>}
                    </>
                }>
                    <Select value={memberUserIdList} mode="multiple" onChange={values => setMemberUserIdList(values)}
                        status={memberUserIdList.length < 3 ? "error" : undefined}>
                        {orgStore.memberList.filter(item => item.parent_depart_ment_id == props.departMentId).map(item => (
                            <Select.Option key={item.member_user_id} value={item.member_user_id}>
                                <Space>
                                    <UserPhoto logoUri={item.logo_uri} style={{ width: "16px", borderRadius: "10px" }} />
                                    {item.display_name}
                                </Space>
                            </Select.Option>
                        ))}
                    </Select>
                </Form.Item>
                <Form.Item label="评估指标" help={
                    <>
                        {targetIdList.length == 0 && <span style={{ color: "red" }}>至少选择一个指标</span>}
                    </>
                }>
                    <Select value={targetIdList} mode="multiple" onChange={values => setTargetIdList(values)}
                        status={targetIdList.length == 0 ? "error" : undefined}>
                        {targetInfoList.map(item => (
                            <Select.Option key={item.target_id} value={item.target_id}>{item.target_name}</Select.Option>
                        ))}
                    </Select>
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default observer(EditEvalModal);